package dao.impl;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.springframework.stereotype.Repository;

import pojo.Customer;
import dao.CustomerDao;

@Repository(value="customerDao")
public class CustomerDaoImpl implements CustomerDao {
	@PersistenceContext(name="un")
	private EntityManager manager;
	
	@Override
	public Customer addCustomer(Customer c) {
		Query query = manager.createQuery("from Customer where name=:name")
				.setParameter("name", c.getName());
		
		if(query.getResultList().size() == 0){
			manager.persist(c);
			return c;
		}
		return null;
	}

	@Override
	public Customer checkCustomer(String name, String password) {
		Query query = manager.createQuery("from Customer where name=:name and password=:password")
				.setParameter("name", name)
				.setParameter("password", password);
		if(query.getResultList().size() == 0){
			return null;
		}
		else{
			Customer c = (Customer)query.getSingleResult();
			return c;
		}
	}

	@Override
	public Customer loadCustomer(String id) {
		return manager.find(Customer.class, id);
	}

	@Override
	public Customer updateCustomer(Customer customer) {
		manager.persist(customer);
		return customer;
	}

}
